<?php

namespace App\Http\Controllers;

use App\GoodsCar;
use App\GoodsNorm;
use App\GoodsSku;
use Illuminate\Http\Request;

class GoodsCarController extends Controller
{
    //
    public function check(Request $request)
    {
        $goodsSku = GoodsSku::where('norm_ids',$request->sku)->first();
        if(!$goodsSku){
            return [
                "error"=>1,
                "info"=>"商品不存在"
            ];
        }
        if($goodsSku->num < $request->sku){
            return [
                "error"=>1,
                "info"=>"商品没货了"
            ];
        }
        if($goodsSku->price*$request->num != $request->allPrice){
            return [
                "error"=>1,
                "info"=>"不要瞎搞"
            ];
        }
        $sku = explode('|',$request->sku);
        $sku_value = '';
        foreach ($sku as $item){
            $sku_value .= " ".GoodsNorm::find($item)->name;
        }

        $res = GoodsCar::where(["user_id"=>\Auth::id(),"sku"=>$request->sku])->first();
        if ($res){
            $res->num = $res->num+$request->num;
            $res->save();
            return [
                "error"=>0,
                "info" => "已加入购物车"
            ];
        }

        $goodsCar = new GoodsCar();
        $goodsCar->user_id = \Auth::id();
        $goodsCar->goods_id = $request->goods_id;
        $goodsCar->num = $request->num;
        $goodsCar->allprice = $request->allPrice;
        $goodsCar->sku = $request->sku;
        $goodsCar->sku_value = $sku_value;
        $goodsCar->goods_sku_id = GoodsSku::where('norm_ids',$request->sku)->first()->id;

        $res = $goodsCar->save();

        if ($res){
            return [
                "error"=>0,
                "info" => "已加入购物车"
            ];
        }

    }

    public function carlist()
    {
        $goodscars = GoodsCar::where('user_id',\Auth::id())->get();
        return view("goods.car",compact("goodscars"));
    }

    public function update(Request $request)
    {
        foreach ($request->goodsCar_id as $key => $value) {
            $goodsCar = GoodsCar::find($value);
            $goodsCar -> num = $request->num[$key];
            $goodsCar ->save();
        }
    }

    public function jiesuan(Request $request)
    {
      $totalMoney = 0;
      foreach ($request->goodsCar_id as $key => $value) {
          $goodsCar = GoodsCar::find($value);
          $totalMoney += $goodsCar -> num * $goodsCar->goodsSku->price;
      }
      if ($totalMoney == $request->totalMoney) {
          return [
            'error'=>0,
            'info'=>'提交完成,请支付'
          ];
      }else{
          return [
            'error'=>1,
            'info' => '价格不对,玩毛线'
          ];
      }

    }


}
